/**
 * 
 */
package org.rockwalrus.ruly;

import java.text.SimpleDateFormat;

import com.google.wave.api.Blip;
import com.google.wave.api.BlipContentRefs;
import com.google.wave.api.ElementType;
import com.google.wave.api.Gadget;
import com.google.wave.api.event.DocumentChangedEvent;

class ParentBasedVotingHandler extends VotingHandler {

    public ParentBasedVotingHandler(String keyword,
                              String replacement,
                              String kind) {
        super(keyword, replacement, kind);
    }

    @Override
    public void handleBlip(SimpleDateFormat f, DocumentChangedEvent e, Blip document) {
        replaceTrigger(document);
        
        Blip b = e.getBlip();
        BlipContentRefs c;

        do {
            b = b.getParentBlip();

            c = b.first(ElementType.GADGET,
                        Gadget.restrictByUrl(VOTING_GADGET));
        } while (c.isEmpty() && !b.isRoot());
        
        Gadget gadget = (Gadget) c.value();
        String deadline = null;
        
        if (gadget != null)
    	deadline = gadget.getProperty("deadline");
        
        if (deadline == null)
            deadline = String.valueOf(Time.addGameHours(e.getTimestamp(), RulyServlet.VOTING_PERIOD));
        
        addVotingGadget(document, deadline);
    }
}